/**
 * 
 */
package com.example.demo1;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/**
 * @Description: Crash catch
 * @author Administrator
 * @date 2017-7-9
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

	private static CrashHandler instance = new CrashHandler();
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	// private Context mContext;
	private App myApp;
	private SharedPreferences sp;

	private CrashHandler() {

	}

	public static CrashHandler getInstance() {
		if (instance == null)
			instance = new CrashHandler();
		return instance;
	}

	public void setCustomCrashHanler(App myApp) {
		this.myApp = myApp;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		// mContext = context;
		// 崩溃时将catch住异常
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	/* 
	 * 
	 */
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		// saveCrash(mContext);
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				Log.e("Crash", "error : ", e);
			}
			AlarmManager mgr = (AlarmManager) myApp
					.getSystemService(Context.ALARM_SERVICE);
			Intent intent = new Intent(myApp.getApplicationContext(),
					MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("crash", "1");
			PendingIntent restartIntent = PendingIntent.getActivity(
					myApp.getApplicationContext(), 0, intent,
					PendingIntent.FLAG_ONE_SHOT);
			mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500,
					restartIntent); // 1秒钟后重启应用
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(1);
		}
	}

	/**
	 * 错误处理,收集错误信息 发送错误报告等操作均在此完成.
	 * 
	 * @param ex
	 * @return true:如果处理了该异常信息;否则返回false.
	 */
	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		// 自定义处理错误信息
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				Toast.makeText(myApp.getApplicationContext(),
						"很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		}.start();
		return true;
	}
}
